package com.leadingsoft.core.config.datasource;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@ConfigurationProperties(prefix = "mybatis.datasource")
@MapperScan(basePackages = { DataSourceConstants.MAPPER_PACKAGE }, sqlSessionFactoryRef = "mybatisSqlSessionFactory")
public class DataSourceConfig {
	private String url;
	private String username;
	private String password;

	/**
	 * @Title: mybatisDataSource
	 * @Description: 创建数据源
	 * @return
	 * @return: DataSource
	 */
	@Bean(name = "mybatisDataSource")
	public DataSource mybatisDataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		return dataSource;
	}
	/**
	 * @Title: mybatisTransactionManager
	 * @Description: 数据源对应的事务
	 * @return
	 * @return: DataSourceTransactionManager
	 */
	@Bean(name = "mybatisTransactionManager")
	public DataSourceTransactionManager mybatisTransactionManager() {
		return new DataSourceTransactionManager(mybatisDataSource());
	}
	/**
	 * @Title: mybatisSqlSessionFactory
	 * @Description: 配置MyBatis的扫描策略
	 * @param mybatisDataSource
	 * @return
	 * @throws Exception
	 * @return: SqlSessionFactory
	 */
	@Bean(name = "mybatisSqlSessionFactory")
	public SqlSessionFactory mybatisSqlSessionFactory(@Qualifier("mybatisDataSource") DataSource mybatisDataSource)
			throws Exception {
		final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(mybatisDataSource);
		sessionFactory.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources(DataSourceConstants.MAPPER_LOCATION));
		return sessionFactory.getObject();
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}
